package com.efounder.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.efounder.activity.ToEvaluateActivity;
import com.efounder.adapter.OrderAdapter;
import com.efounder.bean.GoodSkusBean;
import com.efounder.bean.OrderBody;
import com.efounder.bean.OrderDetail;
import com.efounder.bean.OrderFoot;
import com.efounder.bean.OrderHead;
import com.efounder.bean.OrderList;
import com.efounder.bean.UpdateOrderBadgeEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.baseui.BaseLazyFragment;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.DialogUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;
import static com.efounder.adapter.OrderAdapter.MALL_DELETE;
import static com.efounder.utils.MallRequestUtil.ORDER_LIST_URL;

/**
 * Created by will on 18-2-2.
 */

public class MallOrderFragment extends BaseLazyFragment {

    private String TAG = this.getClass().getSimpleName();
    private View rootView;
    private SmartRefreshLayout xRefreshView;
    private LinearLayout llNetworkErrorView, llMallNoOrder;
    private TextView tvReload;
    private RecyclerView recyclerView;
    private OrderAdapter orderAdapter;
    private OrderList orderList;
    private List<Object> formatOrderList = new ArrayList<>();
    private List<String> storeInfos = new ArrayList<>();
    private int num = 0;
    private int pageSize = 7;
    private String status = "all";
    /*夺宝订单类型*/
    public static final int ORDER_TYPE_TREASURE = 2;
    /**
     * 虚拟商品的订单类型
     */
    public static final int ORDER_TYPE_VIRTUAL = 3;
    /**
     * 新的虚拟商品的订单类型
     */
    public static final int ORDER_TYPE_NEW_VIRTUAL = 4;

    public MallOrderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.layout_frag_order, container, false);
        if (this.getArguments() != null) {
            status = this.getArguments().getString("status");
        }
        llNetworkErrorView = (LinearLayout) rootView.findViewById(R.id.ll_network_error);
        llMallNoOrder = (LinearLayout) rootView.findViewById(R.id.ll_mall_no_order);
        tvReload = (TextView) rootView.findViewById(R.id.tv_network_reload);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData(false);
            }
        });
        xRefreshView = rootView.findViewById(R.id.xRefreshView);
        xRefreshView.setEnableRefresh(true);
        xRefreshView.setEnableLoadMore(true);
        xRefreshView.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                initData(true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData(false);
            }
        });
        recyclerView = (RecyclerView) rootView.findViewById(R.id.order_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        orderAdapter = new OrderAdapter(getActivity(), formatOrderList);
        orderAdapter.setOnOrderAdapterListener(new OrderAdapter.OnOrderAdapterListener() {
            @Override
            public void onRebuy() {
                rebuy();
            }

            @Override
            public void cancleOrder(final int position, final List<OrderBody> orderBodies) {//取消订单

                DialogUtil.showDialogWithCancle(getActivity(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                goToCancleOrder(position, orderBodies);
                            }
                        }, getResources().getString(R.string.mail_cancle_buy), getResources().getString(R.string.mall_or_sure_cancle_buy),
                        getResources().getString(R.string.mail_sure), getResources().getString(R.string.cancle));

            }

            @Override
            public void onConfirmOrder(final int position, final List<OrderBody> orderBodies) {//确认收货

                DialogUtil.showDialogWithCancle(getActivity(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                goToConfirmOrder(position, orderBodies);
                            }
                        }, getResources().getString(R.string.common_text_hint), getResources().getString(R.string.mall_confirm_order),
                        getResources().getString(R.string.mail_sure), getResources().getString(R.string.cancle));

            }

            @Override
            public void onComment(int position, final List<OrderBody> orderBodies) {//评价
                Intent intent = new Intent(getContext(), ToEvaluateActivity.class);
                intent.putExtra("orderBh", orderBodies.get(0).getOrderBh());
                startActivity(intent);
            }

            @Override
            public void onDeleteOrder(final int position, final List<OrderBody> orderBodies) {//删除订单
                DialogUtil.showDialogWithCancle(getActivity(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                goToDeleteeOrder(position, orderBodies);
                            }
                        }, getResources().getString(R.string.mail_delete_order), getResources().getString(R.string.mall_delete_order_confirm),
                        getResources().getString(R.string.mail_sure), getResources().getString(R.string.cancle));
            }
        });
        recyclerView.setAdapter(orderAdapter);
        return rootView;
    }

    private List<OrderBody> deleteUnuseredOrder(List<OrderBody> orderBodies) {
        Set<OrderBody> set = new TreeSet<>(new Comparator<OrderBody>() {
            @Override
            public int compare(OrderBody o1, OrderBody o2) {
                return o1.getOrderBh().compareTo(o2.getOrderBh());
            }
        });
        set.addAll(orderBodies);
        return new ArrayList<OrderBody>(set);

    }

    //取消订单
    private void goToCancleOrder(final int position, List<OrderBody> orders) {
        LoadingDataUtilBlack.show(getActivity(), getString(R.string.common_text_please_wait));
        //去除重复订单
        List<OrderBody> orderBodies = deleteUnuseredOrder(orders);
        JSONArray jsonArray = new JSONArray();
        try {
            for (OrderBody orderBody : orderBodies) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orderbh", orderBody.getOrderBh());
                jsonObject.put("status", "cannelOrder");
                jsonArray.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orders", jsonArray.toString());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.CHANGE_ORDER_STATUS_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if ("success".equals(jsonObject.getString("result"))) {
                        initData(false);
                    } else {
                        ToastUtil.showToastCenter(getResources().getString(R.string.mall_cancle_fail));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_cancle_fail));
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToastCenter(getResources().getString(R.string.mall_cancle_fail));
            }
        });

    }

    //删除订单
    private void goToDeleteeOrder(final int position, List<OrderBody> orders) {
        LoadingDataUtilBlack.show(getActivity(), getString(R.string.common_text_please_wait));
        //去除重复订单
        List<OrderBody> orderBodies = deleteUnuseredOrder(orders);
        JSONArray jsonArray = new JSONArray();
        try {
            for (OrderBody orderBody : orderBodies) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orderbh", orderBody.getOrderBh());
                jsonObject.put("status", "deleteOrder");
                jsonArray.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orders", jsonArray.toString());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.CHANGE_ORDER_STATUS_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if ("success".equals(jsonObject.getString("result"))) {
                        initData(false);
                    } else {
                        ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_oreder_fail));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_oreder_fail));
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_oreder_fail));
            }
        });

    }

    //确认收货
    private void goToConfirmOrder(final int position, List<OrderBody> orders) {
        LoadingDataUtilBlack.show(getActivity(), getString(R.string.common_text_please_wait));
        //去除重复订单
        List<OrderBody> orderBodies = deleteUnuseredOrder(orders);
        JSONArray jsonArray = new JSONArray();
        try {
            for (OrderBody orderBody : orderBodies) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orderbh", orderBody.getOrderBh());
                jsonObject.put("status", "enterReceived");
                jsonArray.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orders", jsonArray.toString());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.CHANGE_ORDER_STATUS_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if ("success".equals(jsonObject.getString("result"))) {
                        initData(false);
                    } else {
                        ToastUtil.showToastCenter(getResources().getString(R.string.mall_confirm_order_fail));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_confirm_order_fail));
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToastCenter(getResources().getString(R.string.mall_confirm_order_fail));
            }
        });

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }


    @Override
    protected void DestroyView() {

    }

    @Override
    protected void onFirstUserVisible() {
        super.onFirstUserVisible();
        LoadingDataUtilBlack.show(getActivity(), getString(R.string.common_text_please_wait));
        initData(false);
    }

    @Override
    protected void onUserVisible() {
        LoadingDataUtilBlack.show(getActivity(), getString(R.string.common_text_please_wait));
        initData(false);

    }

    @Override
    public void onFirstUserInvisible() {
        super.onFirstUserInvisible();
        if (orderAdapter != null && formatOrderList != null) {
            formatOrderList.clear();
            orderAdapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void onUserInvisible() {
        if (orderAdapter != null && formatOrderList != null) {
            formatOrderList.clear();
            orderAdapter.notifyDataSetChanged();
        }

    }


    public void initData(final boolean hasMore) {

        if (!hasMore) {
            num = 0;
        } else {
            num = num + pageSize;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("status", status);
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("num", num + "");
        map.put("pageSize", pageSize + "");
        MallRequestUtil.getRequest(TAG, ORDER_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                llNetworkErrorView.setVisibility(View.GONE);
                Gson gson = new GsonBuilder().serializeNulls().create();
                orderList = gson.fromJson(response, OrderList.class);
                if (!hasMore) {
                    formatOrderList.clear();
                }
                if (orderList == null || orderList.getOrders() == null) {
                    llMallNoOrder.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                } else {
                    if (orderList.getOrders().size() > 0) {
                        formatOrderData(orderList);
                    } else if (!hasMore) {
                        recyclerView.setVisibility(View.GONE);
                        llMallNoOrder.setVisibility(View.VISIBLE);
                    } else {
                        ToastUtil.showToast(getActivity(), R.string.mail_no_more_data);
                        xRefreshView.finishLoadMoreWithNoMoreData();
                    }
                }
                xRefreshView.finishLoadMore();
                xRefreshView.finishRefresh();
                EventBus.getDefault().post(new UpdateOrderBadgeEvent());
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                llNetworkErrorView.setVisibility(View.VISIBLE);
                xRefreshView.finishLoadMore();
                xRefreshView.finishRefresh();
            }
        });
    }

    private void formatOrderData(OrderList orderList) {
        llMallNoOrder.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
        for (OrderList.OrdersBean ordersBean : orderList.getOrders()) {
            if (MALL_DELETE.equals(ordersBean.getPaymentStatus())) {
                continue;
            }
            //头数据
            OrderHead orderHead = new OrderHead();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
                    format(new Date(Long.valueOf(ordersBean.getPayOrderDate())));
            orderHead.setOrderDate(date);
            orderHead.setOrderBh(ordersBean.getOrderBh());
            orderHead.setOrderStatus(ordersBean.getPaymentStatus());
            orderHead.setShopName(ordersBean.getItems().get(0).getGood().getMallShop().getShopName());
            orderHead.setShopBrandlog(ordersBean.getItems().get(0).getGood().getMallShop().getShopBrandlog());
            formatOrderList.add(orderHead);

            List<OrderBody> orderBodies = new ArrayList<>();

            //商品数据
            for (int i = 0; i < ordersBean.getItems().size(); i++) {
                OrderList.OrdersBean.ItemsBean.GoodBean goodBean = ordersBean.getItems().get(i).getGood();
                OrderBody orderBody = new OrderBody();
                orderBody.setOrderImg(goodBean.getGoodCover());
                if (ordersBean.getOrderType() == ORDER_TYPE_TREASURE) {
                    orderBody.setOrderMark(ResStringUtil.getString(R.string.mall_win_treasure));
                }
                orderBody.setOrderNum(String.valueOf(ordersBean.getItems().get(i).getGoodNum()));
                orderBody.setPriceUnit(ordersBean.getItems().get(i).getGood().getMallGoodPrice().getPriceUnit());
                if (goodBean.getGoodSkus() != null && goodBean.getGoodSkus().size() > 0) {
                    List<GoodSkusBean.AttributeContentListBean> attrList = goodBean.getGoodSkus().get(0).getAttributeContentList();
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int j = 0; j < attrList.size(); j++) {
                        stringBuilder.append(attrList.get(j).getVIdName())
                                .append("；");
                    }
                    if(stringBuilder.length()>1){
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    }

                    orderBody.setOrderModel(stringBuilder.toString());
                    orderBody.setSkuId(goodBean.getGoodSkus().get(0).getSkuId());
                    orderBody.setOrderPrice(goodBean.getGoodSkus().get(0).getSkuPrice());
                    orderBody.setOrderTitle(goodBean.getGoodSkus().get(0).getPropertiesName());
                } else {
                    orderBody.setOrderModel(goodBean.getDescription());
                    orderBody.setOrderPrice(goodBean.getMallGoodPrice().getPrice());
                    orderBody.setSkuId("1");
                    orderBody.setOrderTitle(goodBean.getGoodName());
                }
                orderBody.setOrderBh(ordersBean.getOrderBh());
                orderBody.setGoodBh(goodBean.getGoodId());
                formatStoreInfo(goodBean, orderBodies, i, orderBody);
            }
            storeInfos.clear();
            //底部数据
            OrderFoot orderFoot = new OrderFoot();
            if (ordersBean.getPaymentDetails() != null &&
                    ordersBean.getPaymentDetails().size() > 0) {
                //已付款
                OrderDetail.OrderBean.PaymentDetailBean paymentDetailBean =
                        ordersBean.getPaymentDetails().get(0);
                if ("0".equals(paymentDetailBean.getSelectPayType())) {
                    //人民币付款
                    orderFoot.setPriceUnit("￥");
                    orderFoot.setAfterDiscountTotalPrice(ordersBean.getAfterDiscountTotalPrice());
                } else {
                    orderFoot.setPriceUnit(paymentDetailBean.getTokenName());
                    orderFoot.setAfterDiscountTotalPrice(paymentDetailBean.getPayTokenAmount());
                }
            } else {
                //待付款
                orderFoot.setPriceUnit(orderBodies.get(0).getPriceUnit());
                orderFoot.setAfterDiscountTotalPrice(ordersBean.getAfterDiscountTotalPrice());
            }
            orderFoot.setOrderTotalNum(ordersBean.getGoodCount());
            orderFoot.setOrderTotalPrice(ordersBean.getTotalPrice());
            orderFoot.setOrderBh(ordersBean.getOrderBh());
            orderFoot.setOrderBodies(orderBodies);
            orderFoot.setOrderType(ordersBean.getOrderType());
            orderFoot.setGoodsId(ordersBean.getItems().get(0).getGood().getGoodId());
            orderFoot.setOrderStatus(orderHead.getOrderStatus());
            formatOrderList.add(orderFoot);
        }
        orderAdapter.notifyDataSetChanged();

    }

    private void formatStoreInfo(final OrderList.OrdersBean.ItemsBean.GoodBean goodBean, List<OrderBody> orderBodies, final int i, final OrderBody orderBody) {
        //店铺信息
        if (!storeInfos.contains(goodBean.getMallShop().getShopBh())) {
            storeInfos.add(goodBean.getMallShop().getShopBh());
//            formatOrderList.add(goodBean.getMallShop());
        }
        formatOrderList.add(orderBody);
        orderBodies.add(orderBody);
    }

    private void rebuy() {
        View contentView;
        LayoutInflater inflater = (LayoutInflater)
                getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
        contentView = inflater.inflate(R.layout.layout_rebuy_pop, null);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        final PopupWindow abortAlert = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        TextView tvAbort = (TextView) contentView.findViewById(R.id.tv_abort_checkout);
        TextView tvResume = (TextView) contentView.findViewById(R.id.tv_resume_checkout);
        tvAbort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                abortAlert.dismiss();
            }
        });
        tvResume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转购物车
                try {
                    abortAlert.dismiss();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.fragment.MallCartFragment"), bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
        abortAlert.setContentView(contentView);
        abortAlert.setFocusable(true);
        abortAlert.setBackgroundDrawable(new BitmapDrawable());
        abortAlert.setOutsideTouchable(false);
        abortAlert.showAtLocation(rootView, Gravity.CENTER, 0, 0);
    }

    @Override
    public void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
}
